package com.xiaodu.springboot.actuator.controller;

import com.google.common.base.Strings;
import org.springframework.stereotype.Controller;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: dutianjie
 * @date: 2021/6/16 21:42
 * @email: xiaoduup@aliyun.com
 */
@Controller
public class DemoController {

    public static void main(String[] args) {
        Long a = 9886751301162505L;

        //9886751301162505L
        System.out.println(a);
        // 打印出科学记数法 9.886751301162504E15
        System.out.println(a.doubleValue());

        NumberFormat numberFormat = NumberFormat.getNumberInstance();
        // 9,886,751,301,162,504
        System.out.println(numberFormat.format(a.doubleValue()));

        System.out.println(BigDecimal.valueOf((double) 9886751301162505L));
        // 使用 bigde
        BigDecimal bigDecimal = BigDecimal.valueOf(a.doubleValue());
        //9886751301162504
        System.out.println(bigDecimal);

        System.out.println(Long.toBinaryString(a));


        System.out.println(longToBinary(9886751301162505L, new StringBuilder()));
        System.out.println(binaryToStr(longToBinary(9886751301162505L, new StringBuilder())));
    }

    private static String longToBinary(long l, StringBuilder sb) {

        if (l < 2 && sb.length() <= 0) {
            return l + "";
        } else if (l == 2 && sb.length() <= 0) {
            return "10";
        } else {
            if (l == 1) {
                sb.append(l);
                return reverse(sb);
            } else {

                sb.append(l % 2);
            }
            return longToBinary(l / 2, sb);
        }
    }

    private static String binaryToStr(String binary) {
        String newBinary = binary;
        if (binary.length() % 8 != 0) {
            newBinary = Strings.repeat("0", binary.length() % 8) + binary;
        }
        char[] chars = newBinary.toCharArray();
        long l = 0;
        for (int i = 0; i < newBinary.length(); i++) {

            if (i == 0) {
                l += 1;
            } else {
                l += Stream.generate(() -> 2L).limit(i).reduce(Long.parseLong(String.valueOf(chars[i])), (a, b) -> a * b);
            }
        }
        return l + "";
    }

    private static String reverse(StringBuilder str) {
        List<String> aa;
        aa = Stream.iterate(0, t -> t + 1)
                .limit(str.length())
                .map(str::charAt)
                .map(Object::toString)
                .collect(Collectors.toList());

        Collections.reverse(aa);
        return aa.stream().collect(Collectors.joining());
    }
}
